﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace MND.Commands
{
    class CommandManager
    {

        public static CommandManager Instance
        {
            get
            {
                if (instance == null)
                    instance = new CommandManager();
                return instance;
            }
        }
        private static CommandManager instance;


        private Dictionary<string, CommandBase> commands = new Dictionary<string, CommandBase>(StringComparer.CurrentCultureIgnoreCase);
        public void RefreshCommands()
        {
            Dictionary<string, CommandBase> refreshedCommands = new Dictionary<string, CommandBase>(StringComparer.CurrentCultureIgnoreCase);

            commands.Clear();
            DirectoryInfo commandDir = new DirectoryInfo("Commands");
            IEnumerable<FileInfo> files = commandDir.GetFiles("*.*", SearchOption.AllDirectories);

            refreshedCommands = files.Where(file => file.Extension == ".xml").Select(file => new CommandBase(file.FullName)).ToDictionary(cbase => cbase.Name);
            /*
            var commandFiles = from file in files
                               where file.Extension == ".xml"
                               select file.FullName;

            foreach (string file in commandFiles)
            {
                CommandBase c = new CommandBase(file);
                refreshedCommands.Add(c.Name, c);
            }
            */
            lock (commands)
            {
                commands = refreshedCommands;
            }
        }

        public void SetCommandBase(UserCommand uc)
        {
            if (uc.Command == String.Empty)
                return;

            var matchingCommands = (from c in commands.Keys
                                    where c.StartsWith(uc.Command,StringComparison.CurrentCultureIgnoreCase)
                                    select c);
            if (matchingCommands.Count() > 0)
            {
                if (uc.User.Config.UseShorthandCommands)
                {
                    var match = matchingCommands.First();
                    uc.Base = commands[match];
                }
                else
                {
                    throw new CommandNotFoundException() {FoundCommands = matchingCommands.ToArray() };
                }
            }
            else
            {
                throw new CommandNotFoundException();
            }
        }
    }
}
